package com.lucenly.card.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lucenly.card.R;
import com.lucenly.card.base.BaseActivity;
import com.lucenly.card.bean.Rule;
import com.lucenly.card.constants.Constants;
import com.lucenly.card.constants.UrlDefend;
import com.lucenly.card.utils.GsonUtil;
import com.lucenly.card.utils.PublicUtil;
import com.lucenly.card.utils.TimeUtils;
import com.lucenly.card.view.CustomHeaderAndFooterPicker;
import com.lucenly.card.view.DatePicker;
import com.lucenly.card.view.NoScrollViewPager;
import com.lucenly.card.view.calendar.calendar.CalendarMonthView;
import com.lucenly.card.view.calendar.calendar.CalendarView;
import com.lucenly.card.view.calendar.calendar.CalendarViewPagerAdapter;
import com.lucenly.card.view.calendar.calendar.CustomDate;
import com.lucenly.card.view.calendar.calendar.OnCalenderListener;
import com.lucenly.card.view.calendar.calendar.RecordState;
import com.siberiadante.toastutils.ToastUtil;
import com.vise.xsnow.dialog.PromptDialog;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.utls.SharedPreferencesUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MonthActivity extends BaseActivity implements OnCalenderListener {
@BindView(R.id.ll_back)
LinearLayout ll_back;
    @BindView(R.id.tv_title)
    TextView tv_title;
    private int cellHeight;
    private int rows = 6;
    @BindView(R.id.ll_all)
    LinearLayout ll_all;
    @BindView(R.id.tv_year)
    TextView tv_year;
    @BindView(R.id.tv_month)
    TextView tv_month;
    @BindView(R.id.ll_month)
    LinearLayout ll_month;
    @BindView(R.id.ll_year)
    LinearLayout ll_year;
    @BindView(R.id.viewpager)
    NoScrollViewPager monthViewPager;
    @BindView(R.id.tv_num)
            TextView tv_num;
    @BindView(R.id.tv_detail)
    TextView tv_detail;
    CalendarMonthView calendarMonthView;
    private CalendarView[] monthViews = new CalendarView[1];
    private Handler mHandler = new Handler();
    List<Long> list = new ArrayList<>();
    PromptDialog dialog;
    String yearStr,monthStr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_month);
    }
    private void setViewPager() {
        calendarMonthView = new CalendarMonthView(this,this);
        calendarMonthView.updata(Integer.parseInt(yearStr.replace("年","")),Integer.parseInt(monthStr.replace("月","")));
        monthViews[0] = calendarMonthView;
        CalendarViewPagerAdapter<CalendarView> viewPagerAdapter = new CalendarViewPagerAdapter<>(monthViews);
        monthViewPager.setAdapter(viewPagerAdapter);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                monthViewPager.requestLayout();
            }
        }, 150);


    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void initView() {
        dialog = new PromptDialog(this);
        ll_back.setVisibility(View.VISIBLE);
        tv_title.setText("打卡记录");
//         calendarMonthView = new CalendarMonthView(this,this);
//        ll_month.addView(calendarMonthView);
        if(Constants.YEAR.equals("")){
            String year = TimeUtils.stampToDate(System.currentTimeMillis() + "", "yyyy年");
            tv_year.setText(year);
            yearStr = year;
        }else{
            tv_year.setText(Constants.YEAR);
            yearStr = Constants.YEAR;
        }
        if(Constants.MONTH.equals("")){
            String month = TimeUtils.stampToDate(System.currentTimeMillis() + "", "MM月");
            tv_month.setText(month);
            monthStr = month;
        }else{
            tv_month.setText(Constants.MONTH);
            monthStr = Constants.MONTH;
        }
        setViewPager();
    }
//    private void setViewPager() {
//
//        CalendarViewPagerAdapter<CalendarView> viewPagerAdapter = new CalendarViewPagerAdapter<>(monthViews);
//        monthViewPager.setAdapter(viewPagerAdapter);
//        monthViewPager.setCurrentItem(498);
//        monthPagerListener = new CalendarViewPagerListener(monthViewPager, viewPagerAdapter);
//        monthViewPager.addOnPageChangeListener(monthPagerListener);
//        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                monthViewPager.requestLayout();
//            }
//        }, 150);
//
//
//    }
    @Override
    protected void bindEvent() {
        C(ll_back);
        C(ll_month);
        C(ll_year);
    }

    @Override
    protected void initData() {
        getData(tv_year.getText().toString().replace("年",""),tv_month.getText().toString().replace("月",""));
        PublicUtil.getRule(Constants.DAKA_TISHI, new ACallback<Rule>() {
            @Override
            public void onSuccess(Rule data) {
                tv_detail.setText(data.detail);
            }

            @Override
            public void onFail(int errCode, String errMsg) {

            }
        });
    }

    private void getData(final String year, final String month) {
        dialog.showLoading("加载中");
        ViseHttp.GET(UrlDefend.DAKA_JILU)
                .addHeader("Token", SharedPreferencesUtil.getInstance().getString("Token"))
                .addParam("month",year+"-"+month+"")
                .request(new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        dialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            list.clear();
                            JSONArray lists = jsonObject.getJSONArray("list");
                            ArrayList<Long> longs = GsonUtil.fromJsonList(lists.toString(), Long.class);
                            list.addAll(longs);
                            tv_num.setText(list.size()+"天");
                            tv_year.setText(year+"年");
                            tv_month.setText(month+"月");
                            calendarMonthView.updata(Integer.parseInt(year),Integer.parseInt(month));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        ToastUtil.showSingletonShort(errMsg);
                        dialog.dismiss();
                    }
                });
    }

    @Override
    protected void processClick(View view) {
        switch (view.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.ll_year:
                CustomHeaderAndFooterPicker picker1 = new CustomHeaderAndFooterPicker(this, DatePicker.YEAR_MONTH);
                picker1.setRangeEnd(Integer.parseInt(yearStr.replace("年","")), Integer.parseInt(monthStr.replace("月","")));
                picker1.setRangeStart(2018, 1);
                picker1.setSelectedItem(Integer.parseInt(tv_year.getText().toString().replace("年","")), Integer.parseInt(tv_month.getText().toString().replace("月","")));
                picker1.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() {
                    @Override
                    public void onDatePicked(String year, String month) {
                        getData(year+"",month+"");
                    }

                });
                picker1.show();
                break;
            case R.id.ll_month:
                CustomHeaderAndFooterPicker picker = new CustomHeaderAndFooterPicker(this, DatePicker.YEAR_MONTH);
                picker.setRangeEnd(Integer.parseInt(yearStr.replace("年","")), Integer.parseInt(monthStr.replace("月","")));
                picker.setRangeStart(2018, 1);
                picker.setSelectedItem(Integer.parseInt(tv_year.getText().toString().replace("年","")), Integer.parseInt(tv_month.getText().toString().replace("月","")));
                picker.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() {
                    @Override
                    public void onDatePicked(String year, String month) {
                        getData(year+"",month+"");
                    }

                });
                picker.show();
                break;
        }
    }

    @Override
    public void clickDate(CustomDate date) {

    }

    @Override
    public void showDate(CustomDate date) {

    }

    @Override
    public void onMeasureCellHeight(int cellSpace) {
        cellHeight = cellSpace;
        if (rows != 0) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) monthViewPager.getLayoutParams();
            lp.height = rows * cellHeight;
            monthViewPager.setLayoutParams(lp);
        }
    }

    @Override
    public void changeRowCount(int rows) {
        this.rows = rows;
        if (cellHeight != 0) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) monthViewPager.getLayoutParams();
            lp.height = rows * cellHeight;
            monthViewPager.setLayoutParams(lp);
        }
    }

    @Override
    public RecordState setSignDateStatus(CustomDate date) {
        boolean isShow = false;
        for (Long timeTemp:
                list) {
            String stamp = TimeUtils.stampToDate(timeTemp*1000+"", "yyyy-MM-dd");
            String[] split = stamp.split("-");
            if(split[1].startsWith("0")){
                split[1] = split[1].replace("0","");
            }
            if(split[2].startsWith("0")){
                split[2] = split[2].replace("0","");
            }
            if(split[0].equals(date.getYear()+"")&&split[1].equals(date.getMonth()+"")&&split[2].equals(date.getDay()+"")){
                isShow = true;
                break;
            }
        }
        if(isShow){
            return RecordState.Sign;
        }
        return RecordState.UnSign;
    }
}
